<!-- 咨询弹窗 -->
<template>
  <a-modal
    :maskClosable="false"
    :title="title"
    centered
    destroyOnClose
    :width="1000"
    v-model="visible"
    :confirmLoading="confirmLoading"
    okText="发布"
    @ok="handleSubmit"
  >
    <a-form-model ref="ruleForm" :model="form" :rules="rules" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-form-model-item label="归属分类">
        <a-cascader
          :fieldNames="{ label: 'module', value: 'id', children: 'children' }"
          :options="moduleOptions"
          v-model="moduleValue"
          :allowClear="false"
          placeholder="请选择发送模块"
        />
      </a-form-model-item>
      <a-form-model-item label="标题" prop="title">
        <a-input v-model="form.title" placeholder="请输入标题" />
      </a-form-model-item>
      <a-form-model-item label="副标题" prop="subtitle">
        <a-input v-model="form.subtitle" placeholder="请输入副标题" />
      </a-form-model-item>
      <a-form-model-item style="height: 140px" label="封面图">
        <UploadImg v-model="form.coverUrl" warehouse cropper :width="125" :height="100" :cropperEnlarge="3">
          <template #tips> 500*400 </template>
        </UploadImg>
      </a-form-model-item>
      <a-form-model-item label="查看身份限制">
        <a-radio-group name="radioGroup" v-model="form.identityLimit">
          <a-radio :value="0">
            不限制
          </a-radio>
          <a-radio :value="1">
            限定会员身份可查看<span style="color: #86909C;">（由于官网不区分会员，限制后不可发布到官网）</span>
          </a-radio>
        </a-radio-group>
        <a-checkbox-group v-if="form.identityLimit" v-model="checkedMemberLevelList">
          <a-row>
            <a-col v-for="item in memberLevelList" :span="12" :key="item.memberLevelId">
              <a-checkbox :value="item.memberLevelId">
                {{ item.memberLevelName }}
              </a-checkbox>
            </a-col>
          </a-row>
        </a-checkbox-group>
      </a-form-model-item>
      <a-form-model-item label="发布平台" prop="application">
        <a-checkbox-group v-model="application" style="width: 100%; line-height: unset">
          <a-row>
            <a-col v-for="item in applicationList" :span="6" :key="item.value">
              <a-checkbox :value="item.value" :disabled="item.disabled">
                {{ item.text }}
              </a-checkbox>
            </a-col>
          </a-row>
        </a-checkbox-group>
      </a-form-model-item>

      <a-form-model-item label="虚拟浏览量">
        <a-input v-model.number="form.virtualBrowseNum" placeholder="请输入虚拟浏览量" />
      </a-form-model-item>
      <a-form-model-item label="发布日期" prop="pubdate">
        <a-date-picker
          v-model="form.pubdate"
          :show-time="{ format: 'HH:mm:ss' }"
          format="YYYY-MM-DD H:mm:ss"
          placeholder="发布时间"
          valueFormat="YYYY-MM-DD HH:mm:ss"
        />
      </a-form-model-item>
      <a-form-model-item label="资讯内容类型">
        <a-radio-group name="radioGroup" v-model="form.linkType">
          <a-radio :value="1">
            关联公众号文章
          </a-radio>
          <a-radio :value="0">
            图文（文案、图片、视频、多个文件）
          </a-radio>
          <a-radio :value="2">
            单个文件
          </a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item v-if="form.linkType === 1" label="跳转链接" prop="linkUrl">
        <a-input v-model="form.linkUrl" placeholder="请输入与小程序同一认证主体的公众号文章链接" />
        <a @click="handleOpenCopyLinkModal">怎么复制链接？</a>
      </a-form-model-item>
      <a-form-model-item v-if="form.linkType === 0" label="资讯详情" prop="details">
        <Ueditor v-if="visible" v-model="form.details" editorId="consult" />
      </a-form-model-item>
      <a-form-model-item v-if="form.linkType === 2" label="文件上传" prop="fileUrl">
        <UploadFile
          :defaultFileList="urlDefaultFileList"
          @uploadSuccess="handleUploadSuccess"
          btnText="文件上传"
          :maxNum="1"
        ></UploadFile>
      </a-form-model-item>
    </a-form-model>
    <CopyLinkModal ref="copyLinkModal" />
  </a-modal>
</template>
<script>
import {
  consultAdd,
  consultEdit,
  informationCategoryList,
  getInformationDtail,
  getMemberLevelList
} from '@/api/content/management'
import CopyLinkModal from './copyLink.vue'
import UploadImg from '@/components/UpFile/uploadImg'
import Ueditor from '@/components/Ueditor'
import moment from 'moment'
import { cloneDeep } from 'lodash-es'
import UploadFile from '@/components/UploadFile/multiple.vue'
import { buildUUID } from '@/utils/uuid'
const initForm = {
  id: undefined,
  module: undefined,
  moduleSub: undefined,
  title: undefined,
  subtitle: undefined,
  coverUrl: undefined,
  application: 'HOME_MINI',
  linkUrl: '',
  linkType: 1,
  virtualBrowseNum: undefined,
  pubdate: moment().format('YYYY-MM-DD HH:mm:ss'),
  details: undefined,
  identityLimit: 0,
  memberLevelList: undefined,
  fileUrl: ''
}

export default {
  components: {
    Ueditor,
    CopyLinkModal,
    UploadImg,
    UploadFile
  },
  data() {
    return {
      showTop: false,
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: {},
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        coverUrl: [{ required: true, message: '请上传封面图', trigger: 'blur' }],
        application: [{ required: true, message: '请选择发布平台', trigger: 'change' }],
        linkUrl: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback('请输入跳转链接')
              } else if (value.length > 200) {
                callback('请勿超过200个字符')
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        // details: [{ required: true, message: '请填写咨询详情', trigger: 'blur' }],
        pubdate: [{ required: true, message: '请选择发布时间', trigger: 'blur' }],
        // subtitle: [{ required: true, message: '请输入副标题', trigger: 'blur' }],
        fileUrl: [{ required: true, message: '请上传文件', trigger: 'blur' }]
      },
      title: '',
      type: 'add',
      // coverUrl: '',
      loading: false,
      enabled: undefined,
      queryParam: {},
      moduleOptions: [],
      applicationList: [
        { text: '官网', value: 'HOME', disabled: false },
        { text: '小程序', value: 'MINI', disabled: false }
        // { text: '小程序,官网', value: 'MINI_HOME' },
      ],
      moment,
      memberLevelList: []
    }
  },
  watch: {
    'form.identityLimit'(val) {
      this.disabledApplication()
    },
    'form.linkType'(val) {
      this.disabledApplication()
      if (this.$refs.ruleForm) {
        this.$refs.ruleForm.clearValidate()
      }
    }
  },
  computed: {
    urlDefaultFileList() {
      return this.form.fileUrl
        ? [
            {
              name: this.form.fileUrl,
              url: this.form.fileUrl,
              uid: buildUUID(),
              status: 'done'
            }
          ]
        : []
    },
    application: {
      get() {
        return this.form.application ? this.form.application.split('_') : []
      },
      set(val) {
        this.form.application = val.join('_')
      }
    },
    moduleValue: {
      get() {
        return this.form.module ? [this.form.module, this.form.moduleSub] : []
      },
      set(val) {
        this.form.module = val[0]
        this.form.moduleSub = val[1]
      }
    },
    checkedMemberLevelList: {
      get() {
        return this.form.memberLevelList ? this.form.memberLevelList.map(item => item.memberLevelId) : []
      },
      set(val) {
        this.form.memberLevelList = this.memberLevelList.filter(item => val.includes(item.memberLevelId))
      }
    }
  },
  beforeCreate() {},
  created() {},

  methods: {
    disabledApplication() {
      if (this.form.identityLimit || this.form.linkType === 2) {
        this.$set(this.applicationList, 0, { ...this.applicationList[0], disabled: true })
        if (this.application.includes('HOME')) {
          this.application = this.application.filter(item => item !== 'HOME')
        }
      } else {
        this.$set(this.applicationList, 0, { ...this.applicationList[0], disabled: false })
      }
    },
    handleUploadSuccess(files) {
      if (files.length) {
        this.form.fileUrl = files[0].url
      } else {
        this.form.fileUrl = ''
      }
    },

    async queryMemberLevelList() {
      const res = await getMemberLevelList()
      this.memberLevelList = res.data
    },
    show(obj) {
      const { module, moduleSub } = obj.data
      this.form = cloneDeep(initForm)

      this.title = obj.title
      this.type = obj.type
      this.visible = true

      this.queryMemberLevelList()
      this.$nextTick(async () => {
        await this.getModule()
        if (obj.type === 'add') {
          this.moduleValue = [module, moduleSub]
          this.form.pubdate = moment().format('YYYY-MM-DD HH:mm:ss')
        } else if (obj.type === 'edit' || obj.type === 'copy') {
          await this.queryInformationDtail(obj.data.id)
        }
      })
    },

    async queryInformationDtail(id) {
      const res = await getInformationDtail(id)
      this.form = res.data
      if (this.form.linkType === null) {
        this.form.linkType = 0
      }
    },
    async getModule() {
      informationCategoryList().then(r => {
        if (typeof r.data !== 'object') return
        this.moduleOptions = r.data
        let item = this.moduleOptions[0]
        if (this.type === 'add' && !this.moduleValue.some(item => item)) {
          this.moduleValue = [item.id, item.children[0].id]
        }
      })
    },
    //显示复制链接弹窗
    handleOpenCopyLinkModal() {
      this.$refs.copyLinkModal.openModal()
    },

    // 发布与编辑内容
    handleSubmit() {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return
        try {
          this.confirmLoading = true
          if (this.form.moduleSub === undefined) {
            this.$message.error('请选择二级咨询分类')
            return
          }
          if (this.type === 'add' || this.type === 'copy') {
            await consultAdd(this.form)
            this.$message.success('新增成功', 1)
            this.$emit('add')
          } else {
            await consultEdit(this.form)
            this.$message.success('编辑成功', 1)
            this.$emit('upd')
          }
          this.visible = false
        } catch (error) {
        } finally {
          this.confirmLoading = false
        }
      })
    }
  }
}
</script>
<style>
/* html {
  overflow: unset !important;
} */
</style>
<style lang="less" scoped>
.tree {
  max-height: 400px;
  overflow: auto;
}

/deep/ .ql-editor {
  height: 200px;
}

/deep/ .edui-editor {
  width: 100% !important;
}
</style>
